package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.HttpTestManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.Task.HttpTask;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class HttpTestWidget extends GeneralTestWidget {
    private ScrollView sView;
    private LinearLayout httpTestDetail;
    private HttpTestManager httpTestManager;
    private LinearLayout chartLayout;
    private Button btnRetest;
    private Button backBtn;
    private Activity ctx;
    private Task task;
    private Handler httpTestHandler;
    private ImageView pointImageView;
	private TextView timesView;
	private TextView timeRateView;
	private TextView sucRateView;
	private int frequency=5;
	private float lastDelaytime = 0;
    public HttpTestWidget(Activity context) { 
        super(context);
        inflate(context, R.layout.http_test_widget, this);
        this.ctx = context;
        backBtn = (Button) findViewById(R.id.http_test_btnBack);
        sView = (ScrollView) this.findViewById(R.id.http_test_ScrView);
        httpTestDetail = (LinearLayout) this.findViewById(R.id.http_test_detail);
        chartLayout = (LinearLayout) this.findViewById(R.id.httpTestChartLayout);
        pointImageView = (ImageView)findViewById(R.id.pointImageView);
        timeRateView = (TextView)findViewById(R.id.timeRateView);
        timesView = (TextView)findViewById(R.id.timesView);
        sucRateView = (TextView)findViewById(R.id.sucRateView);
     //   btnRetest = (Button) findViewById(R.id.btn_http_retest);
        httpTestManager = new HttpTestManager(ctx);

        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // back(ctx);
             	switch(GlobalApp.nowNetType) {
 				case 1:
 					backToTestWidget_Wlan(ctx);
 					break;
 				case 2:
 					backToTestWidget_TD(ctx);
 					break;
 				case 3:
 					backToTestWidget_GSM(ctx);
 					break;
 				default:
 					break;
 				}
             }
        });

        // 定义HTTP 测试句柄，获得每次测试结果
        httpTestHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.HTTP_PAGELOAD_SUCCESS:
                    updateHttpTestResult();
                    setScrollViewDown(sView);
                    break;
                case MessageWhat.HTTP_PAGELOAD_FAILED:
                    dismissProgressDialog();
                    showMessage(ctx,"HTTP测试加载失败.");
                    break;
                case MessageWhat.DONE:
                    drawLineChart();
                    setScrollViewDown(sView);
                    dismissProgressDialog();
                    break;
                case MessageWhat.NETWORK_INVALID:
                    dismissProgressDialog();
                    showMessage(ctx, "无法连接至因特网.");
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    dismissProgressDialog();
                    showMessage(ctx, "无法获取FTP账号，请检查FTP配置.");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                    dismissProgressDialog();
                    showMessage(ctx, "上传成功.");
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    dismissProgressDialog();
                    showMessage(ctx, "上传失败，请检查FTP配置是否正确.");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    dismissProgressDialog();
                    showMessage(ctx, "FTP登录失败，请检查FTP配置是否正确.");
                    break;
                }
            }
        };
        httpTestManager.setHandler(httpTestHandler);

        task = new Task();
    }

    public void startHttpTest() { 
        timeRateView.setText("0 s");
        timesView.setText(0+"/"+frequency+"次");
        sucRateView.setText("0 Kb/s");
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp!=null && ftp.userName!=null && ftp.userName.length() > 0) {
           // this.showProgressDialog(ctx, "正在进行HTTP测试...", 5);
            int type = NetworkManager.detectNetworkConnectivity(ctx);
            if (type == -1) {
                sendMsg(MessageWhat.NETWORK_INVALID, httpTestHandler); 
            } else {
                //initTask(task, ctx, type);
                new Thread() {
                    public void run() {
                        task.startTime = StringUtils.getDateTime();
                        httpTestManager.startHttpTest("http://www.baidu.com", frequency);
                    }

                }.start();
            }

        }
    }

    private void drawLineChart() {
        DecimalFormat df = new DecimalFormat("#0.000");
        StringBuffer result = new StringBuffer();
        int times = httpTestManager.getXdata().length;
        long size = httpTestManager.getPageLength();
        float delay = (float)httpTestManager.totalDelayTime / times;
        float speed = (delay == 0) ? 0 : ((float) size *1000 / 1024) / delay;
        speed *=8;
        // Log.e("", String.valueOf(size));
        result.append("测试次数=").append(times);
        result.append(",平均时延=").append(df.format(delay / 1000));
        result.append(" s");
        result.append(",平均下载速率=").append(df.format(speed)).append(" Kb/s");
        TextView tv = new TextView(ctx);
        tv.setTextSize(13);
        tv.setTextColor(Color.BLUE);
        tv.setText(result);
        httpTestDetail.addView(tv);
        
        task.testCount = 5;
        HttpTask httpTask = task.newHttpTask("www.baidu.com");
        httpTask.delay = df.format(delay / 1000);
        httpTask.failedTimes = 0;
        ArrayList<HttpTask> httpTasks = new ArrayList<HttpTask>(1);
        httpTasks.add(httpTask);
        task.httpTasks = httpTasks;
        task.endTime = StringUtils.getDateTime();

        int max = getMax(httpTestManager.getYdata());
        ChartManager cm = new ChartManager(ctx, 6, max);
        
        //ChartManager cm = new ChartManager(ctx, 5, 20);
        String chartTitle = "HTTP页面访问测试";
        String[] lineTitles = new String[] { "页面访问时延" };
        List<double[]> x = new ArrayList<double[]>(1);
        List<double[]> y = new ArrayList<double[]>(1);
        x.add(httpTestManager.getXdata());
        y.add(httpTestManager.getYdata());
        int[] colors = new int[] { Color.GREEN };
        View lineChart = cm.createLineChart(colors, chartTitle, lineTitles, x, y);
        
        chartLayout.addView(lineChart);

    }

    private void updateHttpTestResult() {
    	int times = httpTestManager.getXdata().length;
        long size = httpTestManager.getPageLength();
        float delay = (float)httpTestManager.totalDelayTime / times;
        float speed = (delay == 0) ? 0 : ((float) size / 1024) / ((float) delay / 1000);
        speed *= 8;
        DecimalFormat df = new DecimalFormat("#0.000");
        int currentTime = httpTestManager.getCurrentTime();
      //  this.setDialogProgress(currentTime);
        long delayTime = httpTestManager.getDelayTime();
        httpTestManager.processing = false;
        StringBuffer sb = new StringBuffer();
        sb.append("第").append(currentTime).append("次 ").append(httpTestManager.getAddress()).append(" 页面访问时延：")
                .append(df.format((float) delayTime / 1000)).append(" s");
        TextView text = new TextView(ctx);
        text.setText(sb);
        text.setTextColor(Color.BLACK);
        text.setTextSize(12);
        //========================================== 
        timeRateView.setText(df.format(delay / 1000)+"s");
        timesView.setText(currentTime+"/"+httpTestManager.getXdata().length+"次");
        sucRateView.setText(df.format(speed)+" Kb/s");
        rotateDialChart((float) delayTime / 1000);
        httpTestDetail.addView(text);
        
    }
    
    public void rotateDialChart(float current){
		
		float start = lastDelaytime;
		float end = 0;
		if (current>=0 && current< 0.5) {
			end = (float)(current/0.1 *18);
		}else if(current >= 0.5 && current < 1) {
			end = 5*18 + (float)((current-0.5)/0.5 *18); 
		}else if(current >=1 && current <3) {
			end = 6*18 +(float)((current-1)/1 *18);
		}else if(current >=3 && current <5) {
			end = 8*18 +(float)((current-3)/2 *18);
		}else if (current >=5 && current <10) {
			end = 9*18 +(float)((current-5)/5 *18);
		}else if(current>=10){
			end = 180f;
		}
		lastDelaytime = end;
	// 旋转动画效果 
		 AnimationSet animation=new AnimationSet(true);
		 RotateAnimation rotateAnimation=new RotateAnimation(start, end,
				Animation.RELATIVE_TO_SELF, 1f,
				Animation.RELATIVE_TO_SELF, 0.25f);
	//	AlphaAnimation alpha=new AlphaAnimation(1, 0);
		/* ScaleAnimation acale=new ScaleAnimation(1, 0.1f, 1,0.1f,
				 Animation.RELATIVE_TO_SELF, 0.5f,
				 Animation.RELATIVE_TO_SELF, 0.5f);
			acale.setDuration(1000);
			animation.addAnimation(acale);*/
		 rotateAnimation.setDuration(500);
		 animation.addAnimation(rotateAnimation);
		 animation.setFillEnabled(true);
		 animation.setFillAfter(true);
	//	 alpha.setDuration(3000);
	//	 animation.addAnimation(alpha);
		 pointImageView.startAnimation(animation); 
	}
}